package com.example.testapplication.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.testapplication.R;
import com.example.testapplication.bean.Person;

import java.util.List;

public class PersonAdapter extends BaseAdapter {
    private Context mContext;  // 上下文
    private List<Person> mList; // 实体类的列表
    private ViewHolder mViewHolder; // 视图缓冲

    // 构造方法
    public PersonAdapter(Context mContext,List<Person> mList){
        this.mContext = mContext;
        this.mList = mList;
    }

    @Override
    public int getCount() {
        return mList.size(); // 列表长度
    }

    @Override
    public Object getItem(int i) {
        return mList.get(i); // 返回元素项
    }

    @Override
    public long getItemId(int i) {
        return i; // 返回元素id
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        final Person person = mList.get(i); // 获取具体项
        if(view == null){
            // 用LayoutInflater 加载布局 传给布局对象
            // 用view找到3个控件 存储在viewHolder
            view = LayoutInflater.from(mContext).inflate(R.layout.person_item,viewGroup,false);
            mViewHolder = new ViewHolder(); // 初始化ViewHolder对象
            mViewHolder.checkBox = view.findViewById(R.id.check_Box);
            mViewHolder.personImage = view.findViewById(R.id.person_image);
            mViewHolder.personName = view.findViewById(R.id.person_name);
            view.setTag(mViewHolder); // 将viewHolder 对象加入到Tag中
        }else{
            mViewHolder = (ViewHolder) view.getTag();
        }
        // 为复选框设置监听事件
        mViewHolder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                person.setCheck(b); // 设置状态
            }
        });
        // 设置具体项的内容
        mViewHolder.personName.setText(person.getName());
        mViewHolder.personImage.setImageResource(person.getImageId());
        mViewHolder.checkBox.setChecked(person.isCheck());
        return view; // 将设置好视图返回
    }

    class ViewHolder{
        ImageView personImage;
        TextView personName;
        CheckBox checkBox;
    }
}
